import React, { Component } from 'react'
import {Table, Button, Modal, Form, Input, message, Select, Upload, Icon} from 'antd'
import {getCategory} from '../../api/category'
const { Option } = Select;

class Category extends Component{
  state = {
    dataSource: [],
    visible: false,
    type: '1'
  }
  getCategoryList = async () => {
    const result = await getCategory()
    if(result.status === 0){
      const dataSource = result.data
      this.setState({
        dataSource
      })
    } else {
      message.error('获取列表失败')
    }
  }
  componentDidMount() {
    this.getCategoryList()
  }
  columns = [
    {
      title: '类别',
      dataIndex: 'name',
      key: 'name',
    },{
      title: '排序',
      dataIndex: 'parentId',
      key: 'sort'
    },{
      title: '操作',
      key: 'action',
      render: (text, record) => (
        <span>
          <Button type="link" size="small">修改</Button>
          <Button type="link" size="small">查看子分类</Button>
        </span>
      ),
    }
  ]
  showModal = () => {
    this.setState({
      visible: true,
    });
  }
  handleCancel = e => {
    this.setState({
      visible: false,
    });
  }
  handleOk = e => {
    this.setState({
      visible: false,
    });
  }
  handleChange = (value) => {
    this.setState({
      type: value
    })
  }
  render() {
    const uploadButton = (
      <div>
        <Icon type={this.state.loading ? 'loading' : 'plus'} />
        <div className="ant-upload-text">点击上传</div>
      </div>
    );
    return (
      <div calssName="category">
        <Button type="primary" style={{marginBottom:'10px'}} onClick={this.showModal}>添加品类</Button>
        <Table dataSource={this.state.dataSource} columns={this.columns} rowKey={row=>row._id} />
        <Modal title="添加品类" visible={this.state.visible} onOk={this.handleOk} onCancel={this.handleCancel}>
          <Form>
            <Form.Item label="添加级别">
              <Select defaultValue={this.state.type} onChange={this.handleChange}>
                <Option value="1">一级分类</Option>
                <Option value="2">二级分类</Option>
              </Select>
            </Form.Item>
            <Form.Item label="分类名称">
              <Input placeholder="请输入分类名称" />
            </Form.Item>
            {this.state.type === '2'?<Form.Item label="分类图片" >
              <Upload name="avatar" listType="picture-card" className="avatar-uploader"
                action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
              >
              {this.state.imageUrl ? <img src={this.state.imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
              </Upload>
            </Form.Item>:null}
            <Form.Item label="分类排序">
              <Input placeholder="请输入分类排序" />
            </Form.Item>
          </Form>
        </Modal>
      </div>
    )
  }
}
export default Form.create()(Category)